/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int dfs(TreeNode* root,long long gain,int target){ //以root为起点得到分数为target的路径条数
        if(!root){
            return 0;
        }

        int ret=0;
        long long gain1=gain+root->val;
        if(gain1==target){
            ret++;
        }

        ret+=dfs(root->left,gain1,target)+dfs(root->right,gain1,target);
        return ret;
    }
    int pathSum(TreeNode* root, int targetsum) {
        if(!root){
            return 0;
        }

        return dfs(root,0,targetsum)+pathSum(root->left,targetsum)+pathSum(root->right,targetsum); //以所有节点为起点得到target路径的总和
    }
};